package com.smbms.controller;


import com.smbms.pojo.Bill;
import com.smbms.service.BIllService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/bill")
public class BillController {
    @Autowired
    private BIllService billService;

    //查询所有
    @GetMapping("/list")
    public String test(HttpSession session) throws Exception{

        List<Bill> billsList = billService.showAll();

        for (Bill b:billsList){
            session.setAttribute("billList",billsList);
            System.out.println(b);
        }
        return "billList";

    }

    @PostMapping("/add")
    public String add(Bill bill, HttpSession session)throws Exception{
        System.out.println(bill);
        boolean isOK = billService.addBill(bill);
        if(isOK){
            session.setAttribute("billList",billService.showAll());
            return "billList";
        }else {
            return "billAdd";
        }
    }

    //添加responsebody，返回数据给前台
    @PostMapping("/del")
    @ResponseBody
    public boolean del(long id,HttpSession session)throws Exception{

        boolean isOK = billService.del(id);

        return isOK;
    }


    @GetMapping("/{id}")
    public String findById(@PathVariable Long id, Model model)throws  Exception{
        model.addAttribute("bills",billService.showBillById(id));
        return "billView";
    }



    @GetMapping("/update/{id}")
    public String updateById(@PathVariable Long id, Model model) throws Exception{
        model.addAttribute("bill",billService.showBillById(id));
        return "billUpdate";
    }


    //保存修改后的数据
    @PostMapping("/{id}")
    public String saveUpdate(Bill bill, @PathVariable long id, HttpSession session, Model model)throws Exception{
        bill.setId(id);
        boolean isOK=billService.updateBill(bill);
        if(isOK){
            session.setAttribute("billList",billService.showAll());
            return "billList";

        }else {
            //修改不成功丢失原有数据，需要重新保存
            model.addAttribute("billList",billService.showBillById(id));
            return "billUpdate";
        }

    }






}
